package com.scribbles.article.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.scribbles.article.service.ArticleSearchService;
import com.scribbles.common.dto.ArticleDTO;
import com.scribbles.common.entity.Article;

@Controller
@RequestMapping(value = "articleSearch")
public class ArticleSearchController {
	
	@Autowired
	private ArticleSearchService articleSearchService;
	
	@RequestMapping(value = "/getArticlesResult", method = RequestMethod.GET)
	public String getArticlesResult() {
		return "article/articleResults";
	}
	
	@RequestMapping(value = "/searchAllArticles")
	public Map<String, ? extends Object> searchArticle() {
		List<Article> articlesList = articleSearchService.retrieveAllArticles();
		Map<String, Object> modelMap = new HashMap<String, Object>();
		List<ArticleDTO> articlesDTOList = convertArticleEntityToDTO(articlesList);
		modelMap.put("success", true);
		modelMap.put("articles", articlesDTOList);
		return modelMap;
	}
	
	
	private List<ArticleDTO> convertArticleEntityToDTO(List<Article> articlesList) {
		List<ArticleDTO> articlesDTOList = new ArrayList<ArticleDTO>();
		for (Iterator iterator = articlesList.iterator(); iterator.hasNext();) {
			Article article = (Article) iterator.next();
			ArticleDTO articleDTO = new ArticleDTO();
			articleDTO.setId(article.getId());
			articleDTO.setArticleHeaderName(article.getArticleHeader().getName());
			articleDTO.setName(article.getName());
			articleDTO.setDescription(article.getDescription());
			articleDTO.setCreatedBy(article.getCreatedBy().getFirstName() + " " + article.getCreatedBy().getLastName());
			articleDTO.setArticleStatus(article.getArticleHeader().getStatus());
			articleDTO.setArticleContent(article.getArticleContent());
			articlesDTOList.add(articleDTO);
		}
		return articlesDTOList;
	}
}
